package com.example.demo.websocket;

import com.example.demo.util.TailLogRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TailLogWebSocketHandler extends TextWebSocketHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final Map<WebSocketSession, Thread> sessionMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String filePath = getFilePathFromSession(session);
        if (!StringUtils.hasLength(filePath)) {
            try {
                logger.info("filePath = {}", filePath);
                session.sendMessage(new TextMessage("文件路径为空，请检查参数"));
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            try {
                session.sendMessage(new TextMessage(filePath + " 文件不存在！"));
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        logger.info("WebSocket连接已建立 - 会话ID: " + session.getId()
                + ", 远程地址: " + session.getRemoteAddress()
                + ", 监控文件: " + filePath);
        Thread tailLog = new Thread(new TailLogRunnable(filePath, session));
        sessionMap.put(session, tailLog);
        tailLog.start();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        Thread thread = sessionMap.get(session);
        if (thread != null) {
            thread.interrupt();
        }
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        sessionMap.remove(session);
        logger.info("WebSocket连接已关闭 - 会话ID: " + session.getId() + ", 关闭原因：" + status);
    }

    private String getFilePathFromSession(WebSocketSession session) {
        String filePath = "chat.log";
        String query = session.getUri().getQuery();
        if (query != null && !query.isEmpty()) {
            Map<String, String> parameters = new HashMap<>(8);
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    parameters.put(keyValue[0], keyValue[1]);
                }
            }
            if (parameters.containsKey("filePath")) {
                filePath = parameters.get("filePath");
            }
        }
        return filePath;
    }

}